import cv2
from Parameter import Parameter


# 这个true的保证是天空
def is_sky(hsv_pixel: tuple) -> bool:
    return (
        hsv_pixel[0] > 115
        and hsv_pixel[0] < 125
        and hsv_pixel[-1] > 50
        and hsv_pixel[1] > 150
        or hsv_pixel[-1] > 225
    )


# 这个true的保证是植物
def is_plant(hsv_pixel: tuple) -> bool:
    return (
        (hsv_pixel[0] < 100 or hsv_pixel[0] > 130)
        and (hsv_pixel[1] < 200)
        and (hsv_pixel[2] < 225)
    )


# 这个true的保证是山
def is_mountain(hsv_pixel: tuple) -> bool:
    return (
        hsv_pixel[0] > 100
        and hsv_pixel[0] < 130
        and hsv_pixel[1] > 60
        or hsv_pixel[-1] > 200
    )


if __name__ == "__main__":
    img_path = Parameter.assetRootDir + "/tree.jpg"
    result_path = Parameter.resultRootDir + "/task3/result.jpg"

    img = cv2.imread(img_path)

    hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    height, width, channel = img.shape
    half_width = width >> 1

    # 这个循环获得glass_line
    for i in range(height):
        line_plant_count = 0
        for j in range(width):
            if is_plant(hsv_img[i, j]):
                line_plant_count += 1
        if line_plant_count > 0.5 * width:
            glass_line = i
            break

    # 创建两边的view，把左边的转为hsv，方便后续copy树
    left_view = img[0:glass_line, 0:half_width]
    hsv_left_view = cv2.cvtColor(left_view, cv2.COLOR_BGR2HSV)
    right_view = img[0:glass_line, half_width:width]

    left_height, left_width, _ = left_view.shape

    # 选择树的部分copy
    for i in range(left_height):
        for j in range(left_width):
            if (
                not is_sky(hsv_left_view[i, j]) or is_plant(hsv_left_view[i, j])
            ) and not (i > 0.95 * left_height and is_mountain(hsv_left_view[i, j])):
                right_view[i, j] = left_view[i, j]

    cv2.imwrite(result_path, img)
